<template>
    <div class="white-box">
        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">对账日期：</span>
                <el-date-picker
                    v-model="area_time"
                    type="daterange"
                    unlink-panels
                    value-format="YYYY-MM-DD"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                />
            </div>
            <div class="task-one__item">
                <span class="task-one__label">会员UID：</span>
                <el-input placeholder="输入会员UID" v-model.trim="user_id" clearable></el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">会员姓名：</span>
                <el-input placeholder="输入会员姓名" v-model.trim="user_name" clearable></el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">手机号码：</span>
                <el-input placeholder="输入手机号" v-model.trim="tel" oninput="value=value.replace(/[^\d]/g,'')" maxlength="11" clearable></el-input>
            </div>
            <div class="task-one__btn task-wrap-btn clearfix">
                <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">搜索</el-button>
                <el-button @click="clickExport">导出</el-button>
            </div>
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
        >
            <el-table-column label="昵称/ID" min-width="150">
                <template #default="{ row }">
                    <p>姓名：{{ row.user_name }}[UID: {{ row.uid }}]</p>
                    <p class="line-one" v-if="row.nickname">昵称：{{ row.nickname }}</p>
                </template>
            </el-table-column>
            <el-table-column label="打包费(元)" min-width="150">
                <template #default="{ row }">
                    <p class="p-money">预售打包费：{{ row.pre_pack_amount || "0.00" }}</p>
                    <p class="p-money">实际打包费：{{ row.pack_amount || "0.00" }}</p>
                </template>
            </el-table-column>
            <el-table-column label="运费(元)" min-width="150">
                <template #default="{ row }">
                    <p class="p-money">预售运费：{{ row.pre_freight || "0.00" }}</p>
                    <p class="p-money">实际运费：{{ row.freight || "0.00" }}</p>
                </template>
            </el-table-column>
            <el-table-column prop="user_pay_amount" label="用户补差(元)" width="130"></el-table-column>
            <el-table-column prop="admin_pay_amount" label="平台打款(元)" width="130"></el-table-column>
            <el-table-column prop="debt_amount" label="多退少补(元)" width="130"></el-table-column>
            <el-table-column prop="note" label="备注" min-width="160"></el-table-column>
            <el-table-column prop="day_label" label="账单日期" width="140"></el-table-column>
            <el-table-column label="操作" width="170" class-name="operation-nav" fixed="right">
                <template #default="{ row }">
                    <el-popconfirm
                        title="是否确定打款？"
                        confirm-button-text="确定"
                        cancel-button-text="取消"
                        @confirm="clickPayment(row)"
                        v-if="row.debt_amount < 0"
                    >
                        <template #reference>
                            <el-button link type="primary" class="theme-btn">打款</el-button>
                        </template>
                    </el-popconfirm>
                    <el-button link type="primary" class="theme-btn" @click="clickEdit(row)">编辑</el-button>
                    <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="clickDel(row)">
                        <template #reference>
                            <el-button link type="primary" class="theme-btn">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>

        <!-- 编辑 -->
        <el-dialog v-model="dialogEdit" title="编辑信息" width="600px" :append-to-body="true" :destroy-on-close="true" @close="closeEdit">
            <el-form ref="ruleEditRef" :model="ruleEditForm" :rules="ruleCheckEdit" label-width="120px">
                <el-form-item label="会员UID">
                    <div>{{ ruleEditForm.uid }}</div>
                </el-form-item>
                <el-form-item label="实际包装费" prop="pack_fee">
                    <el-input
                        v-model.trim="ruleEditForm.pack_fee"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        clearable
                        placeholder="请输入整数或小数(保留两位小数)"
                    />
                </el-form-item>
                <el-form-item label="实际运费" prop="logistics_fee">
                    <el-input
                        v-model.trim="ruleEditForm.logistics_fee"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        clearable
                        placeholder="请输入整数或小数(保留两位小数)"
                    />
                </el-form-item>
                <el-form-item label="备注" prop="reason">
                    <el-input v-model.trim="ruleEditForm.reason" type="textarea" clearable :rows="4" placeholder="请输入备注" />
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 20px">
                        <el-button type="primary" :loading="form_loading" @click="submitEditForm(ruleEditRef)"> 确认 </el-button>
                        <el-button @click="resetEditForm(ruleEditRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive, watch } from "vue"
import { Search } from "@element-plus/icons-vue"
import OneLoad from "@mixins/one-load"
import GoBack from "@components/GoBack.vue"

const { proxy } = getCurrentInstance()

onMounted(() => {
    getList()
})

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, search_btn, pubParams, pubRefreshParams, getdata } = OneLoad()
// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})

function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
        uid: user_id.value,
        so: user_name.value,
        mobile: tel.value,
        s_time: area_time.value ? area_time.value[0] : "",
        l_time: area_time.value ? area_time.value[1] : "",
    }
    getdata("finance/user_debt/index", params)
}

/**
 * 搜索
 * @param {String} user_name 会员名称
 * @param {String} user_id 会员ID
 * @param {String} area_time 对账日期
 * @param {String} tel 手机号
 */
const user_name = ref("")
const user_id = ref("")
const area_time = ref("")
const tel = ref("")
const handleSearch = () => {
    search_btn.value = true
    pubRefreshParams(getList)
}

/**
 * 编辑
 * @param {Boolean} dialogEdit 弹窗显示状态
 * @param {Boolean} form_loading 提交按钮状态
 * @param {Array} ruleEditRef 表单规则
 * @param {Object} ruleEditForm  表单字段
 * @param {Object} ruleCheckEdit  表单提示
 * @param {Function} submitEditForm 提交表单
 */
const dialogEdit = ref(false)
const form_loading = ref(false)
const ruleEditRef = ref(null)
const ruleEditForm = reactive({
    debt_id: "",
    uid: "",
    pack_fee: "",
    logistics_fee: "",
    reason: "",
})
const ruleCheckEdit = reactive({
    pack_fee: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    logistics_fee: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    // reason: [{ required: true, message: "请输入备注", trigger: "blur" }],
})
const submitEditForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = {
                debt_id: ruleEditForm.debt_id,
                uid: ruleEditForm.uid,
                pack_amount: ruleEditForm.pack_fee,
                freight: ruleEditForm.logistics_fee,
                note: ruleEditForm.reason,
            }
            proxy.$axios
                .post("finance/user_debt/update", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogEdit.value = false
                        proxy.$message({ message: "编辑成功！", type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetEditForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const closeEdit = () => {
    dialogEdit.value = false
    resetEditForm(ruleEditRef.value)
}
const clickEdit = (row) => {
    ruleEditForm.debt_id = row.debt_id
    ruleEditForm.uid = row.uid
    ruleEditForm.pack_fee = row.pack_amount
    ruleEditForm.logistics_fee = row.freight
    dialogEdit.value = true
}

// 打款
const clickPayment = proxy.$util.throttle((row) => {
    proxy.$axios
        .post("finance/user_debt/remit", {
            debt_id: row.debt_id,
        })
        .then((res) => {
            if (res.data.code == 0) {
                proxy.$message({ message: "打款成功", type: "success" })
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}, 500)

// 删除
const clickDel = (row) => {
    proxy.$axios
        .post("finance/user_debt/delete", {
            debt_id: row.debt_id,
        })
        .then((res) => {
            if (res.data.code == 0) {
                proxy.$message({ message: "删除成功", type: "success" })
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 导出
const clickExport = () => {
    proxy.$axios
        .get("finance/user_debt/export", {
            params: {
                uid: user_id.value,
                so: user_name.value,
                mobile: tel.value,
                s_time: area_time.value ? area_time.value[0] : "",
                l_time: area_time.value ? area_time.value[1] : "",
            },
            responseType: "blob",
        })
        .then(function (res) {
            let contentDisposition = res.headers["content-disposition"]
            let filename = decodeURI(contentDisposition.split("fileName=")[1] || contentDisposition.split("filename=")[1])
            let blob = new Blob([res.data], { type: res.headers["content-type"] })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement("a")
            link.href = url
            link.download = filename
            document.body.appendChild(link)
            link.click()
            URL.revokeObjectURL(url) // 释放内存
            document.body.removeChild(link)
        })
        .catch((err) => {})
}
</script>
<script>
export default {
    name: "MemberBill",
}
</script>

<style lang="less" scoped>
.p-money {
    font-size: @font-size-md;
    em {
        font-size: 13px;
    }
}
</style>
